package com.scedu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scedu.entity.Permission;
import com.scedu.entity.Role;
import com.scedu.entity.User;
import com.scedu.mapper.UserDao;


import com.scedu.result.ProfileResult;
import com.scedu.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sc
 * @since 2020-04-21
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {


    @Autowired
    private  UserDao userDao;

    @Override
    //根据用户名查找用户
    public User findByUserName(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return userDao.selectOne(wrapper);
    }

    @Override
    //获取用户权限的名称列表
    public List<String> findPermissionNamesByUid(String uid) {
        List<Permission> permissionList=userDao.findPermissionByUid(uid);
        List<String> permissions=new ArrayList<>();
        permissionList.forEach(obj -> permissions.add(obj.getPermissionName()));
        return permissions;
    }
    @Override
    //获取用户权限的访问url列表
    public List<String> findPermissionUrlsByUid(String uid) {
        List<Permission> permissionList=userDao.findPermissionByUid(uid);
        List<String> permissions=new ArrayList<>();
        permissionList.forEach(obj -> permissions.add(obj.getUrl()));
        return permissions;
    }
    @Override
    //获取用户的角色列表
    public List<String> findRolesByUid(String uid) {
        List<Role> roleListList=userDao.findRolesByUid(uid);
        List<String> roles=new ArrayList<>();
        roleListList.forEach(obj -> roles.add(obj.getRoleName()));
        return roles;
    }

    @Override
    //返回用户角色权限信息
    public ProfileResult CreateProfileResult(User user) {
        ProfileResult profileResult=new ProfileResult();
        profileResult.setSex(user.getSex());
        profileResult.setRealname(user.getRealname());
        profileResult.setUsername(user.getUsername());
        List<String> roles=findRolesByUid(user.getId()); //角色列表
        List<String> permissionNames=findPermissionNamesByUid(user.getId()); //权限名称列表
        List<String> PermissionUrls=findPermissionUrlsByUid(user.getId()); //权限URL列表
        Map<String,Object> hashroles =new HashMap<>();
        hashroles.put("roles",roles); //角色列表
        hashroles.put("permissionNames",permissionNames);//权限名称列表
        hashroles.put("PermissionUrls",PermissionUrls);//可访问地址列表
        profileResult.setRoles(hashroles);
        return profileResult;
    }
}
